package br.quest.maps;

import java.util.List;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import br.quest.R;
import br.quest.models.Route;
import br.quest.models.Waypoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class RouteOverlay extends Overlay {

    private static final int COLOR = Color.parseColor("#809c97e2");
    private List<Waypoint> points;
    private Route route;
    private Paint paint;
    private Point point;

    public RouteOverlay(Route route, MapView mv) {
        this.route = route;
        point = new Point();
        paint = new Paint();
        paint.setColor(COLOR);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeWidth(10);
        points = this.route.getWaypoints();
    }

    public List<Waypoint> getWaypoints() {
        return points;
    }

    @Override
    public void draw(Canvas canvas, MapView mv, boolean shadow) {
        shadow = false;
        super.draw(canvas, mv, shadow);
        drawPath(mv, canvas);

    }

    public void drawPath(MapView map, Canvas canvas) {
        int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
        for (int i = 0; i < points.size(); i++) {
            map.getProjection().toPixels(points.get(i).getGeoPoint(), point);
            x2 = point.x;
            y2 = point.y;
            if (i == 0) {
                drawMarker(map, canvas, x2, y2, R.drawable.marker_start);
            } else if ((i + 1) == points.size()) {
                drawMarker(map, canvas, x2, y2, R.drawable.marker_end);
            }
            if (i > 0) {
                canvas.drawLine(x1, y1, x2, y2, paint);
            }
            x1 = x2;
            y1 = y2;
        }
    }

    private void drawMarker(MapView map, Canvas canvas, int x, int y, int resource) {
        Bitmap bmp = BitmapFactory.decodeResource(map.getResources(), resource);
        x = x - (bmp.getWidth() / 2);
        y = y - bmp.getHeight();
        canvas.drawBitmap(bmp, x, y, paint);
    }

}
